package net.sourceforge.jweb.jstl.fn;

public class MathUtil {
	private MathUtil() {
	}

	public static double e() {
		return Math.E;
	}

	public static double pi() {
		return Math.PI;
	}

	/**
	 * 求两个数的最小公倍数
	 * 
	 * @param n1
	 *            整型数1
	 * @param n2
	 *            整型数2
	 * @return 两个数的最大公约数
	 */
	public static int GCD(int num1, int num2) {
		if (num2 == 0)
			return 1;
		int residue = num1 % num2;
		if (residue == 0)
			return num2;
		return GCD(num2, residue);
	}

	/**
	 * 找一个整型数组的最大公约数
	 * 
	 * @param arrayInt
	 *            一个整型的数组
	 * @return 最大公约数<br>
	 *         如果没有找到,将返回0
	 */
	public static int GCD(int[] arrayInt) {
		int length = arrayInt.length;
		if (length == 1)
			return arrayInt[0];
		if (length == 2)
			return GCD(arrayInt[0], arrayInt[1]);
		int temp = GCD(arrayInt[0], arrayInt[1]);
		for (int i = 2; i < length; i++) {
			temp = GCD(temp, arrayInt[i]);
		}
		return temp;
	}

	public static int LCM(int n1, int n2) {
		return (n1 * n2) / GCD(n1, n2);
	}

	public static int LCM(int divs[]) {
		if (divs.length == 1)
			return divs[0];
		int res = LCM(divs[0], divs[1]);
		for (int i = 2; i < divs.length; i++)
			res = LCM(res, divs[i]);
		return res;
	}

	/**
	 * 获得一个正整数可以被2整除几次
	 * 
	 * @param val
	 * @return
	 */
	public static int approximateLog2(int val) {
		if (val <= 0)
			return Integer.MIN_VALUE;
		int ret = 0;
		while (val != 1) {
			val >>= 1;
			ret++;
		}
		;
		return ret;
	}

	/**
	 * 求一个正整数能被x整除几次
	 * 
	 * @param val
	 *            被除数
	 * @param x
	 *            除数
	 * @return 正除结果
	 */
	public static int approximateLogx(int val, int x) {
		if (val <= x || val < 0 || x <= 0)
			return 0;
		if (x == 1)
			return val;
		int ret = 0;
		while (val >= x) {
			val /= x;
			ret++;
		}
		return ret;
	}

	public static Integer mode(Integer a, Integer b) {
		if (b == 0)
			return a;
		return a % b == 0 ? a / b : a / b + 1;
	}

	public static Integer parseInt(String source) {
		try {
			return Integer.parseInt(source);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static Short parseShort(String source) {
		try {
			return Short.parseShort(source);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static Float parseFloat(String source) {
		try {
			return Float.parseFloat(source);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0f;
		}
	}

	public static Long parseLong(String source) {
		try {
			return Long.parseLong(source);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0l;
		}
	}

	public static Double parseDouble(String source) {
		try {
			return Double.parseDouble(source);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0d;
		}
	}
}
